package com.loan.controller;

import com.loan.common.WebUtils;
import com.loan.dto.Result;
import com.loan.entity.User;
import com.loan.repository.UserRepository;
import com.loan.util.HashKit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by huxudong on 17/7/12.
 */
@Controller
public class LoginController {

    @Autowired
    private UserRepository userRepository;

    /**
     * 登录页面
     * @param model
     * @return
     */
    @RequestMapping(value = "" , method = RequestMethod.GET)
    public String login(Model model){
        return "login";
    }

    /**
     * 登录处理
     * @param
     * @return
     */
    @RequestMapping(value = "dologin" , method = RequestMethod.POST)
    @ResponseBody
    public Result dologin(String username , String password , HttpServletRequest request , HttpServletResponse response){
        Result result = new Result();
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            result.setCode(2001);
            result.setMessage("请输入正确的内容");
        }else{
            password = HashKit.md5(password);
            User user = userRepository.findByUsernameAndPasswordAndFlag(username,password,0);
            if(user==null){
                result.setCode(2001);
                result.setMessage("用户不存在或密码错误");
            }else{
                WebUtils.loginUser(request, response, user, true);
                result.setMessage("登录成功");
                result.setCode(200);
            }
        }
        return result;
    }


    /**
     * 登出方法改为ajax方式登出
     * @param request
     * @param response
     */
    @ResponseBody
    @PostMapping("logout")
    public void  logout(HttpServletRequest request,HttpServletResponse response){
        WebUtils.logoutUser(request,response);
    }


    /**
     * 404
     * @return
     */
    @RequestMapping(value = "404",method = RequestMethod.GET)
    public String error(Model model) {
        return "404";
    }
}
